<template>
  <div id="mapContainer">
    <MapComponent
      ref="ref_map"
      :typeName="type"
      iconName="realTile"
      :userInfo="userInfo"
      @getDeviceCarMap="getDeviceCarMap"
      @initDrawLayer="initDrawLayer"/>
  </div>

</template>

<script>
    import {transform} from 'ol/proj.js'
    import MapComponent from "../components/MapComponent";
    import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer'
    import XYZ from 'ol/source/XYZ'
    import Feature from "ol/Feature";
    import Point from "ol/geom/Point";
    import VectorSource from "ol/source/Vector";
    import {Icon, Style} from 'ol/style';
    import car from '@/assets/images/marker/car.png'
    import wheelbarrow from '@/assets/images/marker/wheelbarrow.png'
    import elevator_car from '@/assets/images/marker/elevator_car.png'
    import work_ladder from '@/assets/images/marker/work_ladder.png'
    import water_release_truck from '@/assets/images/marker/water_release_truck.png'
    import end from '@/assets/images/marker/end.png'
    import start from '@/assets/images/marker/start.png'
    import pass from '@/assets/images/marker/pass.png'
    import user from '@/assets/images/marker/user.png'

    export default {
        name: "Index",
        components: {
            MapComponent
        },
        data() {
            return {
                map: {},
                mapParameter: {
                    // mapUrl: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}',
                    mapUrl: 'http://www.google.cn/maps/vt?lyrs=s@189&gl=en&x={x}&y={y}&z={z}',
                    lngCenter: 103.9535836,
                    latCenter: 30.5822868,
                    zoom: 13,
                    minZoom: 2,
                    maxZoom: 23,
                    from_epsg: 'EPSG:4326',
                    to_epsg: 'EPSG:3857',
                    iconStyles: {
                        // 'route': new Style({
                        //   stroke: new Stroke({
                        //     width: 4, color: [237, 212, 0, 0.8]
                        //   })
                        // }),
                        // 车图标

                        'powerless': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                scale: 0.4,
                                src: car
                            })
                        }),
                        //人图标
                        'user': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                scale: 0.4,
                                src: user
                            })
                        }),
                        // 客梯车
                        'elevator_car': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                scale: 0.4,
                                src: elevator_car
                            })
                        }),
                        // 放水车
                        'water_release_truck': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                scale: 0.4,
                                src: water_release_truck
                            })
                        }),
                        // 手推车
                        'wheelbarrow': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                scale: 0.4,
                                src: wheelbarrow
                            })
                        }),
                        // 工作梯
                        'work_ladder': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                scale: 0.4,
                                src: work_ladder
                            })
                        }),
                        'start': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                src: start
                            })
                        }),
                        'end': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                src: end
                            })
                        }),
                        'pass': new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                src: pass
                            })
                        })
                    }
                },
                mapLayer: {},
                carNumber: '',//车辆编号
                carType: '',//车辆类型
                dept: '',//部门
                lng: '103.3432423',//当前人员经纬度
                lat: '30.2321334',//当前人员经纬度
                userName: '',//人员姓名
                userId: '',//人员id
                updateTime: '',//人员坐标更新时间
                deptName: '',//所属单位
                type: '',//判断是车辆还是人员
                userInfo: Object,
                device: {
                    carNumber: undefined,
                    locationNumber: undefined,
                    motionStill: 1,
                    carType: {},
                    company: undefined
                },
                companies: [],


            }
        },
        mounted() {
            // this.getPointData()
        },
        created() {
            // 地址栏：`http://localhost:9527/#/newPage?LIFNR=1000000524`
            //获取地址栏参数
            this.type = this.getUrlKey('type')?this.getUrlKey('type'):'';
            console.log(this.type, 'typecresa')
            if (this.type === 'car') {
                this.dept = this.getUrlKey('dept');
                this.carNumber = this.getUrlKey('carNumber');
                this.carType = this.getUrlKey('carType');

                //人员信息
                this.lng = this.getUrlKey('lng');
                this.lat = this.getUrlKey('lat');
                this.userName = this.getUrlKey('userName');
                this.userId = this.getUrlKey('userId');
                this.updateTime = this.getUrlKey('updateTime');
                this.deptName = this.getUrlKey('deptName');
                this.userInfo = {
                    lng: this.lng,
                    lat: this.lat,
                    userName: this.userName,
                    userId: this.userId,
                    updateTime: this.updateTime,
                    deptName: this.deptName,
                }
            } else if (this.type === 'user') {
                this.lng = this.getUrlKey('lng');
                this.lat = this.getUrlKey('lat');
                this.userName = this.getUrlKey('userName');
                this.userId = this.getUrlKey('userId');
                this.updateTime = this.getUrlKey('updateTime');
                this.deptName = this.getUrlKey('deptName');
                this.userInfo = {
                    lng: this.lng,
                    lat: this.lat,
                    userName: this.userName,
                    userId: this.userId,
                    updateTime: this.updateTime,
                    deptName: this.deptName
                }
                console.log(this.userInfo, 'useriiii')
            }
        },
        methods: {
            // 获取url地址后的参数
            getUrlKey(name) {
                return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
            }, //这样就拿到了参数中的数据,
          /**
           * 设置地图中心点
           */
          setCenter (gisInfo) {
            console.log(gisInfo)
            const view = this.map.getView()
            const result = this.$refs.ref_map.transformSelf(gisInfo.lng, gisInfo.lat)
            view.setCenter(result)
          },
            getDeviceCarMap(map, mapParameter, mapLayer) {
                this.map = map
                this.mapParameter = mapParameter;
                console.log(this.mapParameter, 'this.mapParameter')
                this.mapLayer = mapLayer
            },
            operationSource(fun) {
                this.$refs.ref_map.operationSource(this.mapLayer.realTile.name, fun);
            },
            /**
             * 初始化 画图 画布
             **/
            initDrawLayer() {
                this.$refs.ref_map.clearSource();
                this.$refs.ref_map.closePopup();
                if (this.type === 'car') {
                    this.getPointData();
                    this.operationSource(source => {
                        const result = this.transformSelf(this.lng, this.lat);
                        const feature = new Feature({
                            type: 'user',
                            geometry: new Point(result)
                        });
                        feature.setProperties({device: {type: 'user'}});
                        source.addFeature(feature);
                    });
                } else if (this.type === 'user') {
                    console.log('hahahhhahah', this.userInfo)
                    this.operationSource(source => {
                        const result = this.transformSelf(this.lng, this.lat);
                        const feature = new Feature({
                            type: 'user',
                            geometry: new Point(result)
                        });
                        // console.log(feature,'feature',source,'source')
                        feature.setProperties({device: {type: 'user'}});
                        source.addFeature(feature);
                    });
                  let gisInfo = {
                    lng: this.lng,
                    lat: this.lat
                  }
                  // console.log(gisInfo,'gisInfo')
                  this.setCenter(gisInfo)
                }

            },
            transformSelf(lng, lat) {
                return transform([lng, lat], this.mapParameter.from_epsg, this.mapParameter.to_epsg)
            },
            /**
             * 加载最后一次设备上报坐标
             */
            initDeviceGisInfo(source, gisInfo) {
                console.log(gisInfo,'gisInfo')
                if (gisInfo) {
                    this.$refs.ref_map.closePopup();
                    const latestLocation = gisInfo.latestLocation;
                    if (latestLocation) {
                        const lng = latestLocation.split(',')[0];
                        const lat = latestLocation.split(',')[1];
                        console.log(latestLocation, 'latestLocation')
                        const result = this.transformSelf(lng, lat);
                        console.log(result, 'result')
                        const feature = new Feature({
                            type: gisInfo.deviceType ? gisInfo.deviceType : 'powerless',
                            geometry: new Point(result)
                        });

                        // console.log(feature,'feature',source,'source')
                        feature.setProperties({device: {deviceGis: gisInfo, type: 'car'}});
                        source.addFeature(feature);
                      let center = {
                        lng: lng,
                        lat: lat
                      }
                      // console.log(gisInfo,'gisInfo')
                      this.setCenter(center)
                    }

                    // console.log('-----------------------')
                    // console.log(feature,'feature',source,'source')
                }
            },
            getPointData() {
                const url = `${baseUrl}/device/findDeviceGisAdvanced?dept=${this.dept}&carType=${this.carType}&carNumber=${this.carNumber}`;
                // const url = `http://192.168.2.119/device/findDeviceByNumber/${this.carNumber}`;

                this.$get(url).then(data => {
                    // console.log(data.obj, 'dddddd')
                    this.gisInfos = data.obj?data.obj:[];
                    console.log(this.gisInfos,'this.gisInfos')
                    this.operationSource(source => {
                        this.gisInfos.forEach(gisInfo => {
                            this.initDeviceGisInfo(source, gisInfo);
                        });
                    });
                });
            }
        }

    }

</script>

<style scoped>
  #mapContainer {
    flex: 1;
    height: 100%;
    width: 100%;
  }

  .ol-popup:after, .ol-popup:before {
    top: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
  }

  .circle-icon {
    margin-right: 3px;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    overflow: hidden;
    background-color: #42b983;
  }

  .ol-popup {
    position: absolute;
    background-color: white;
    -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
    filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
    /*padding: 15px;*/
    border-radius: 10px;
    border: 1px solid #cccccc;
    bottom: 12px;
    left: -50px;
    min-width: 280px;
    margin-bottom: 10px;
    z-index: 4;
    padding: 20px;
  }

  .ol-popup:after, .ol-popup:before {
    top: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
  }

  .ol-popup:after {
    border-top-color: white;
    border-width: 10px;
    left: 48px;
    margin-left: -10px;
  }

  .ol-popup:before {
    border-top-color: #cccccc;
    border-width: 11px;
    left: 48px;
    margin-left: -11px;
  }

  .ol-popup-closer {
    text-decoration: none;
    position: absolute;
    top: 6px;
    right: 8px;
  }

  .ol-popup-closer:after {
    content: "✖";
    color: #888;
  }

  .title-box {
    display: flex;
    padding-bottom: 10px;
    align-items: center;
    color: #262626;
    font-size: 14px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    border-bottom: 1px solid #ccc;
  }

  .circle-icon {
    margin-right: 3px;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    overflow: hidden;
    background-color: #42b983;
  }

  .popup-content-item {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    height: 30px;
    line-height: 30px;
    font-size: 12px;
    color: #999;
  }

  .span-item {
    flex: 1;
  }
</style>
